package com.sh.secondhand;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.example.zhouwei.library.CustomPopWindow;
import com.sh.Application.BaseApplication;
import com.sh.adapter.DeliveryAddressAdapter;
import com.sh.struts.DeliveryAddressData;
import com.sh.utils.BackgroundManagerUtils;
import com.sh.utils.Utils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class DeliveryAddressManagerActivity extends AppCompatActivity {
    private static final String TAG = "DeliveryAddressManager";
    private static final Integer OPERATION_CODE = 1500;

    private List<DeliveryAddressData> dataList;
    private LinearLayoutManager mLayoutManager;
    private DeliveryAddressAdapter mAdapter;
    private CustomPopWindow popWindow;
    private Intent intent;

    @BindView(R.id.delivery_address_view)
    RecyclerView deliveryAddresses;
    @BindView(R.id.toolbar)
    Toolbar toolbar;

    boolean showPop = true;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_delivery_address_manager);
        ButterKnife.bind(this);
        intent = getIntent();
        showPop = intent.getBooleanExtra("show_pop",true);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        dataList = new ArrayList<>();
        initRecyclerView();
        refreshData();
    }

    private void initRecyclerView() {
        deliveryAddresses.setNestedScrollingEnabled(false);
        mLayoutManager = new LinearLayoutManager(DeliveryAddressManagerActivity.this);
        mAdapter = new DeliveryAddressAdapter(this, new ArrayList<>());

        deliveryAddresses.setLayoutManager(mLayoutManager);
        deliveryAddresses.setAdapter(mAdapter);
    }

    private void openAddOrModify(Integer deliveryAddressId) {
        Intent intent = new Intent(DeliveryAddressManagerActivity.this, AddOrModifyDeliveryAddressActivity.class);
        intent.putExtra("delivery_address_id", deliveryAddressId);
        startActivityForResult(intent, OPERATION_CODE);
    }

    private void refreshData() {
        dataList.clear();
        mAdapter.clearData();
        if(showPop) {
            mAdapter.setOnItemClickListener(new DeliveryAddressAdapter.ItemClickListener() {
                @Override
                public void onItemClick(int position, View view) {
                    View contentView = LayoutInflater.from(DeliveryAddressManagerActivity.this).inflate(R.layout.delivery_address_modify_popupwindow, null);
                    handleLogic(contentView, mAdapter.getItemByPosition(position));
                    popWindow = new CustomPopWindow.PopupWindowBuilder(DeliveryAddressManagerActivity.this)
                            .setView(contentView)
                            .setFocusable(true)
                            .setOutsideTouchable(true)
                            .create()
                            .showAsDropDown(view, 0, 10);
                }
            });
        }else{
            mAdapter.setOnItemClickListener(new DeliveryAddressAdapter.ItemClickListener() {
                @Override
                public void onItemClick(int position, View view) {
                    openAddOrModify(mAdapter.getItemByPosition(position).id);
                }
            });
        }

        mAdapter.buttonSetOnclick(new DeliveryAddressAdapter.ButtonInterface() {
            @Override
            public void buttonClick() {
                openAddOrModify(0);
            }
        });
        new DeliveryAddressInfo().execute((Void) null);
    }

    private void handleLogic(View contentView, DeliveryAddressData deliveryAddressData) {
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.btn_choose: {
                        intent.putExtra("delivery_address", deliveryAddressData);
                        setResult(RESULT_OK,intent);
                        popWindow.dissmiss();
                        finish();
                        break;
                    }
                    case R.id.btn_edit: {
                        openAddOrModify(deliveryAddressData.id);
                        break;
                    }
                    default:
                        break;
                }
            }
        };
        Button choose = contentView.findViewById(R.id.btn_choose);
        Button edit = contentView.findViewById(R.id.btn_edit);
        choose.setOnClickListener(listener);
        edit.setOnClickListener(listener);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == OPERATION_CODE) {
                if ("refresh".equals(data.getStringExtra("operation"))) {
                    refreshData();
                }
            }
        }
    }

    public class DeliveryAddressInfo extends AsyncTask<Void, Void, Void> {
        public Integer userId;

        public DeliveryAddressInfo() {
            if (Utils.checkLogin()) {
                userId = BaseApplication.getLoginInfo().getUserId();
            }
        }

        @Override
        protected Void doInBackground(Void... voids) {
            List<Map<String, String>> resMap = BackgroundManagerUtils.getDeliveryAddress(userId);
            for (Map map : resMap) {
                dataList.add(new DeliveryAddressData(map));
            }
            runOnUiThread(() -> {
                mAdapter.addItems(dataList);
                mAdapter.notifyDataSetChanged();
            });
            return null;
        }
    }
}
